package org.nestor.demo.service;


import io.grpc.stub.StreamObserver;
import org.nestor.demo.protobuf.ChatMessage;
import org.nestor.demo.protobuf.ChatServiceGrpc;

public class ChatServiceImpl extends ChatServiceGrpc.ChatServiceImplBase {

    @Override
    public StreamObserver<ChatMessage> chat(StreamObserver<ChatMessage> responseObserver) {
        // 返回一个StreamObserver处理来自客户端的消息
        return new StreamObserver<ChatMessage>() {

            @Override
            public void onNext(ChatMessage message) {
                // 每收到客户端的一条消息，就响应一条
                System.out.println(Thread.currentThread().getName() + ":Received from " + message.getUser() + ": " + message.getMessage());

                // 服务端可以立刻回应，也可以延迟回应（这里立刻回应）
                ChatMessage reply = ChatMessage.newBuilder()
                        .setUser("Server")
                        .setMessage("Ack: " + message.getMessage())
                        .build();
                responseObserver.onNext(reply);
            }

            @Override
            public void onError(Throwable t) {
                System.err.println("Error from client: " + t.getMessage());
            }

            @Override
            public void onCompleted() {
                // 客户端发送完毕，服务端要通知流也完成
                responseObserver.onCompleted();
            }
        };
    }
}
